package com.nulldev.util.image2.filters.glitch;

import java.awt.image.BufferedImage;

import com.nulldev.util.image2.ImageFilter;

public class LegacyGlitchFilter extends ImageFilter {

	public static final String[] commands = {"generateBlank", "generate"};
	public int rate = 2;
	public boolean merge = true;
	
	@Override
	public BufferedImage process(final String command, final BufferedImage input) {
		BufferedImage out = cloneCoreImage(input);
		if (command.equals("generateBlank")) {
			out = make(input.getWidth(), input.getHeight());
		}else if (command.equals("generate")) {
			out = make(input, input.getWidth(), input.getHeight());
		}else {
			out = make(input.getWidth(), input.getHeight());
		}
		return out;
	}
	
	public BufferedImage processMerge(final BufferedImage input, final BufferedImage input2) {
		return make(input, input2, input.getWidth(), input.getHeight());
	}
	
	private BufferedImage make(BufferedImage img, BufferedImage toMerge, int w, int h) {
		final BufferedImage instance = img;
		for (int i = 0; i < h; i++) {
			int v = getRandomNumberFrom(0, rate);
			for (int b = 0; b < w; b++) {
				if (v == 0) {
					instance.setRGB(b, i, toMerge.getRGB(b, i));
				}else if (v == 1 && merge) {
					instance.setRGB(b, i, invert(instance.getRGB(b, i)));
				}else {
					instance.setRGB(b, i, instance.getRGB(b, i));
				}
			}
		}
		return instance;
	}

	private BufferedImage make(int w, int h) {
		final BufferedImage instance = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		for (int i = 0; i < h; i++) {
			for (int b = 0; b < w; b++) {
				instance.setRGB(b, i, invert(instance.getRGB(b, i)));
			}
		}
		return instance;
	}
	
	private BufferedImage make(BufferedImage img, int w, int h) {
		final BufferedImage instance = img;
		for (int i = 0; i < h; i++) {
			int v = getRandomNumberFrom(0, rate);
			for (int b = 0; b < w; b++) {
				if (v == 0) {
					instance.setRGB(b, i, randomColor().getRGB());
				}else if (v == 1 && merge) {
					instance.setRGB(b, i, invert(instance.getRGB(b, i)));
				}else {
					instance.setRGB(b, i, instance.getRGB(b, i));
				}
			}
		}
		return instance;
	}
}
